package cn.tedu.deviceservice.start;

import cn.tedu.charging.common.pojo.vo.StationInfoVO;
import cn.tedu.deviceservice.dao.repository.StationRepository;
import cn.tedu.deviceservice.pojo.po.StationPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.geo.Point;
import org.springframework.data.redis.core.BoundGeoOperations;
import org.springframework.data.redis.core.GeoOperations;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.PostMapping;

import javax.annotation.PostConstruct;
import java.io.Serializable;
import java.math.BigDecimal;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Slf4j
@Component
public class StationDataInit implements ApplicationRunner {
    @PostConstruct
    public void start(){
        log.debug("自动执行...............");
    }

    @Autowired
    private StationRepository stationRepository;
    @Autowired
    private RedisTemplate<String, Serializable> redisTemplate;

    /**
     * 程序启动,自动执行的代码
     * @param args
     * @throws Exception
     */
    @Override
    public void run(ApplicationArguments args) throws Exception {
        log.debug("程序启动,自动执行的方法");
        List<StationPO> stationPOS= stationRepository.listStation();
        log.debug("查询结果:{}",stationPOS);

        //把站点和坐标信息以geo类型存入redis
        Map<String,Point> points = new HashMap<>();
        BoundGeoOperations stations = redisTemplate.boundGeoOps("stations");
        //站点详情信息按hash类型存入
        HashOperations<String, Object, Object> opsForHash = redisTemplate.opsForHash();
        //遍历信息存储
        for (StationPO stationPO : stationPOS) {
            //使用redis的GEO结构,存储经纬度和站点id
            BigDecimal stationLng = stationPO.getStationLng();
            BigDecimal stationLat = stationPO.getStationLat();
            log.debug("经度:{},纬度:{}",stationLng,stationLat);
            String id = String.valueOf(stationPO.getId());
            Point  point = new Point(Double.parseDouble(String.valueOf(stationLng)),
                    Double.parseDouble(String.valueOf(stationLat)));
            points.put(id,point);
            //把充电站详细信息存入
            Map<String,Object>stationInfo=new HashMap<>();
            stationInfo.put("name",stationPO.getStationName());
            stationInfo.put("deviceNumber",stationPO.getDeviceNumber());
            stationInfo.put("stationCode",stationPO.getStationCode());
            stationInfo.put("operatorId",stationPO.getOperatorId());
            log.debug("站点详细信息:{}",stationInfo);
            opsForHash.putAll(id,stationInfo);
        }
        log.debug("所有的站点经纬度信息:{}",points);
        //存进redis
        stations.add(points);
    }
}
